<?php

namespace app\common\cachemodel\zl4;

use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zl4HoroscopeGoodTimeIsNew extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl4_horoscope_good_time_is_new';

    protected $cacheModel = 'horoscope.good_time_report';

    /**
     * 获取小红点状态
     * @param int $uid
     * @return int[]
     * @throws \Exception
     */
    public function getIsNewStatusCacheData(int $uid)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('home_is_new', $uid)
            ->getDataAndSet(function () use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid])->find();
                    if ($data)
                    {
                        return [
                            'id' => (int)$data['id'],
                            'uid' => (int)$data['uid'],
                            'is_new' => (int)$data['is_new'],
                        ];
                    } else
                    {
                        return [
                            'id' => 0,
                            'uid' => $uid,
                            'is_new' => 0,
                        ];
                    }
                }
                catch (\Exception $e)
                {
                    Log::write('Zl4HoroscopeGoodTimeIsNew model => getIsNewStatusCacheData()异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                    return [];
                }
            }, ['id', 'is_new'], 'home_is_new');

        return $data ? [
            'id' => (int)$data['id'],
            'is_new' => (int)$data['is_new'],
        ] : [
            'id' => 0,
            'is_new' => 0,
        ];
    }

    /**
     * 设置小红点状态
     * @param int $uid
     * @param int $isNew
     * @throws \Exception `
     */
    public function setNewStatus(int $uid, int $isNew)
    {
        $newInfo = $this->getIsNewStatusCacheData($uid);

        if ($newInfo['id'] > 0)
        {   // 有过小红点 状态记录
            $this->where(['id' => $newInfo['id']])->update(['is_new' => $isNew]);
        } else
        {   // 之前没有记录
            $this->insert([
                'uid' => $uid,
                'is_new' => $isNew,
            ]);
        }
        // 删除小红点记录 缓存
        CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('home_is_new', $uid)->rmCache('home_is_new');
    }
}